<template>
  <n-grid cols="1" responsive="screen">
    <n-grid-item>
      <n-card title="基本设置" class="mb-4">
        <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
          <n-form-item label="API Key" path="apiKey">
            <n-input
              v-model:value="formValue.apiKey"
              placeholder="请输入AI服务的API Key"
              type="password"
              show-password-on="click"
              clearable
            />
          </n-form-item>
        </n-form>
      </n-card>

      <div>
        <n-space>
          <n-button type="primary" @click="formSubmit" :loading="loading"> 保存设置</n-button>
          <n-button @click="loadSettings"> 重置</n-button>
        </n-space>
      </div>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { invoke } from '@tauri-apps/api/core';

  interface AISettings {
    apiKey: string;
  }

  const rules = {
    apiKey: {
      validator: (rule: any, value: string) => {
        if (value && value.length < 10) {
          return new Error('API Key长度不能少于10个字符');
        }
        return true;
      },
      trigger: 'blur',
    },
  };

  const formRef: any = ref(null);
  const message = useMessage();
  const loading = ref(false);

  const formValue = reactive<AISettings>({
    apiKey: '',
  });

  // 加载AI设置
  async function loadSettings() {
    try {
      const settings = await invoke<any>('get_user_settings');
      Object.assign(formValue, {
        apiKey: settings.ai_settings?.api_key || '',
      });
      message.success('设置加载成功');
    } catch (error) {
      console.error('加载设置失败:', error);
      message.error('加载设置失败');
    }
  }

  // 保存AI设置
  async function saveSettings() {
    try {
      loading.value = true;
      // 先获取当前完整设置
      const currentSettings = await invoke<any>('get_user_settings');

      const success = await invoke<boolean>('save_user_settings', {
        settings: {
          nickname: currentSettings.nickname || '',
          theme: currentSettings.theme || 'light',
          database: currentSettings.database || {
            host: 'localhost',
            port: 1521,
            service_name: 'ORCL',
            username: 'AH_SLM4',
            password: '2',
          },
          auto_login: currentSettings.auto_login || {
            environments: {
              env_55: 'http://10.243.165.55:8080',
              env_54: 'http://10.243.165.54:8085',
              localhost: 'http://localhost:8080',
            },
            database: {
              host: 'localhost',
              port: 1521,
              service_name: 'ORCL',
              username: 'AH_SLM4',
              password: '2',
            },
          },
          ai_settings: {
            api_key: formValue.apiKey,
          },
        },
      });

      if (success) {
        message.success('设置保存成功');
      } else {
        message.error('设置保存失败');
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      message.error(`保存设置失败: ${error}`);
    } finally {
      loading.value = false;
    }
  }

  // 表单提交
  function formSubmit() {
    formRef.value.validate((errors: any) => {
      if (!errors) {
        saveSettings();
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 组件挂载时加载设置
  onMounted(() => {
    loadSettings();
  });
</script>

<style lang="less" scoped>
  .n-form {
    max-width: 600px;
  }

  .mb-4 {
    margin-bottom: 16px;
  }
</style>
